package com.qf.service.impl;

import com.qf.dao.CarDao;
import com.qf.dao.GoodsDao;
import com.qf.dao.impl.CarDaoImpl;
import com.qf.dao.impl.GoodsDaoImpl;
import com.qf.pojo.Cart;
import com.qf.pojo.Goods;
import com.qf.service.CarService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CarServiceImpl implements CarService {
    @Override
    public boolean createCart(Integer uid, Integer pid) {
        CarDao carDao=new CarDaoImpl();
        Cart cart=carDao.findCartByUidAndPid(uid,pid);

        GoodsDao goodsDao=new GoodsDaoImpl();
        Goods goods=goodsDao.findById(pid);

        if(cart!=null){
            cart.setNum(cart.getNum()+1);
            cart.setGoods(goods);
            cart.setMoney(cart.getNum()*goods.getPrice());
            carDao.updateCart(cart);
        }else {
            cart =new Cart();
                cart.setUid(uid);
                cart.setPid(pid);
                cart.setNum(1);
                cart.setGoods(goods);
                cart.setMoney(cart.getNum()*goods.getPrice());
                carDao.insertCart(cart);
        }
        return true;
    }

    @Override
    public List<Cart> findCartListByUid(Integer uid) {
        CarDao carDao=new CarDaoImpl();
        List<Cart> cartList= carDao.findCartListByUid(uid);
        GoodsDao goodsDao=new GoodsDaoImpl();
        List<Goods> goodsList = goodsDao.findGoodsAll();
//        if(cartList!=null){
//            for(Cart cart:cartList){
//                for(Goods goods: goodsList){
//                    if(cart.getPid()==goods.getId()){
//                        cart.setGoods(goods);
//                    }
//                }
//            }
//        }
        Map<String,Goods> goodsMap=new HashMap<String,Goods>();
        if(goodsList!=null){
            for (Goods goods:goodsList){
                goodsMap.put(String.valueOf(goods.getId()),goods);
            }
        }
        if(cartList!=null){
            for (Cart cart:cartList){
                Goods goods = goodsMap.get(String.valueOf(cart.getPid()));
                if(goods!=null){
                    cart.setGoods(goods);
                }
            }
        }
        return cartList;
    }

    @Override
    public void updateCart(Integer cid, Integer num) {
        CarDao carDao=new CarDaoImpl();
        Cart cart = carDao.findById(cid);
        GoodsDao goodsDao=new GoodsDaoImpl();
        Goods goods = goodsDao.findById(cart.getPid());

        cart.setNum(num);
        cart.setGoods(goods);
        cart.setMoney(goods.getPrice()*num);
        carDao.updateCart(cart);
    }

    @Override
    public void deleteById(Integer id) {
        CarDao carDao=new CarDaoImpl();
        carDao.deleteById(id);
    }
}
